package com.buy.service.Impl;

import com.buy.dao.InstantBuyDao;
import com.buy.exception.MsgException;
import com.buy.service.InstantBuyService;
import com.common.domain.InstantBuyItem;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-24 15:26
 * @description
 * @copyright 2021
 */
@Service
public class InstantBuyServiceImpl implements InstantBuyService {
  @Autowired private InstantBuyDao instantBuyDao;

  @Autowired private RabbitTemplate rabbitTemplate;

  @Autowired private StringRedisTemplate stringRedisTemplate;

  @Override
  public List<InstantBuyItem> queryItems() {
    return instantBuyDao.selectItems(new Date());
  }

  @Override
  public InstantBuyItem queryItem(String itemId) {
    return instantBuyDao.selectItem(itemId, new Date());
  }

  @Override
  public void startBuy(String itemId, String username) {
    Boolean exists = stringRedisTemplate.hasKey("INSTANT_" + itemId);
    if (exists == null || !exists) {
      throw new MsgException("秒杀商品不存在");
    }
    //    number表示被秒杀的数量数量减一
    long number = stringRedisTemplate.opsForHash().increment("INSTANT_" + itemId, "number", -1);
    if (number < 0) {
      if (number == Long.MIN_VALUE) {
        //        防止溢出
        stringRedisTemplate.delete("INSTANT_" + itemId);
        throw new MsgException("秒杀商品已售完");
      }
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date startTime = null;
      Date endTime = null;
      try {
        startTime =
            df.parse(
                (String) stringRedisTemplate.opsForHash().get("INSTANT_" + itemId, "start_Time"));
        endTime =
            df.parse(
                (String) stringRedisTemplate.opsForHash().get("INSTANT_" + itemId, "end_Time"));
      } catch (Exception e) {
        e.printStackTrace();
        throw new MsgException("日期格式异常");
      }
      Date nowTime = new Date();
      if (nowTime.compareTo(startTime) < 0) {
        throw new MsgException("秒杀活动还未开始");
      }
      if (nowTime.compareTo(endTime) > 0) {
        throw new MsgException("秒杀活动已结束");
      }
      //同一用户不能频繁秒杀同一商品
      Boolean itemUser = stringRedisTemplate.hasKey(itemId + username);
      if (itemUser == null || itemUser) {
        throw new MsgException("您已经参与过秒杀活动，不可再参与");
      }
      //剩余商品数量大于0
      String result =
          (String)
              rabbitTemplate.convertSendAndReceive(
                  "instantBuyExchange", "instantBuy", itemId + username);
      if (result != null && result.equals(itemId + username + "SUCCESS")) {
        stringRedisTemplate.opsForValue().set(itemId + username, "SUCCESS", 1, TimeUnit.HOURS);
      } else {
        throw new MsgException("秒杀失败");
      }
    }
  }
}
